from PIL import Image, ImageEnhance, ImageFilter
import pytesseract

def preprocess_image(image):
    # 转换为灰度图
    image = image.convert('L')
    # 应用高斯模糊滤波器去除噪声
    image = image.filter(ImageFilter.GaussianBlur(radius=1))
    # 增强对比度
    enhancer = ImageEnhance.Contrast(image)
    image = enhancer.enhance(2.0)  # 对比度系数可以根据需要调整
    # 增强亮度
    enhancer = ImageEnhance.Brightness(image)
    image = enhancer.enhance(1.5)  # 亮度系数可以根据需要调整
    # 二值化处理
    threshold = 155  # 二值化阈值，可根据实际情况调整
    image = image.point(lambda x: 0 if x < threshold else 255)
    return image

def png_to_text(image_path):
    # 打开图片
    img = Image.open(image_path)
    # 预处理图片
    img = preprocess_image(img)
    # 使用 Tesseract 进行文字识别，添加自定义配置
    custom_config = r'--oem 3 --psm 6'
    text = pytesseract.image_to_string(img, lang='chi_sim+eng', config=custom_config)
    return text

def save_text_to_file(text, file_path):
    # 将文本写入文件
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(text)

# 使用示例
text = png_to_text('C:/Users/yra/Desktop/MathVecCluster/data/image/2019年北京市中考数学试卷pdf2word.png')
save_text_to_file(text, 'C:/Users/yra/Desktop/MathVecCluster/data/txt/2019年北京市中考数学试卷pdf2word.txt')
